﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PominaScale.DataAccess;
using PominaScale.Models;
using CrystalDecisions.CrystalReports.Engine;
using Excel = Microsoft.Office.Interop.Excel;

namespace PominaScale.Reports
{
    public partial class FrmViewReport : Form
    {
        #region Member variables
        SortType sort = SortType.None;
        IList<POModel> poList;
        #endregion

        #region Constructos

        public FrmViewReport()
        {
            InitializeComponent();

            cboProductName.Submit += new KeyEventHandler(cboProduct_SelectedValueChanged);
            cboVendorName.Submit += new KeyEventHandler(cboVendor_SelectedValueChanged);
            
            this.btnViewReport.Click += new EventHandler(btnViewReport_Click);
            this.btnExcel.Click += new EventHandler(btnExcel_Click);
            this.btnClose.Click += new EventHandler(delegate { this.Close(); });

            rdoDate.CheckedChanged += new EventHandler(rdoReport_CheckedChanged);
            rdoProduct.CheckedChanged += new EventHandler(rdoReport_CheckedChanged);
            rdoVendor.CheckedChanged += new EventHandler(rdoReport_CheckedChanged);
            rdoVehicle.CheckedChanged += new EventHandler(rdoReport_CheckedChanged);
            rdoPO.CheckedChanged += new EventHandler(rdoReport_CheckedChanged);
            rdoSummary.CheckedChanged += new EventHandler(rdoReport_CheckedChanged);
            rdoNhapHang.CheckedChanged += new EventHandler(rdoReport_CheckedChanged);
            rdoXuatHang.CheckedChanged += new EventHandler(rdoReport_CheckedChanged);

            rdoSortDate.CheckedChanged += new EventHandler(rdoSortReport_CheckedChanged);
            rdoSortMH.CheckedChanged += new EventHandler(rdoSortReport_CheckedChanged);
            rdoSortNCC.CheckedChanged += new EventHandler(rdoSortReport_CheckedChanged);
            rdoSortPO.CheckedChanged += new EventHandler(rdoSortReport_CheckedChanged);
            rdoSortWeight.CheckedChanged += new EventHandler(rdoSortReport_CheckedChanged);
            rdoSortCategory.CheckedChanged += new EventHandler(rdoSortReport_CheckedChanged);

            this.groupBox1.Enabled = false;

            // Load combos
            this.LoadCombos();
        }

        #endregion

        #region Events

        private void rdoSortReport_CheckedChanged(object sender, EventArgs e)
        {
            if (sender is RadioButton)
            {
                RadioButton radioSortReport = sender as RadioButton;
                switch (radioSortReport.Name)
                {
                    case "rdoSortDate":
                        sort = SortType.Date;
                        break;
                    case "rdoSortMH":
                        sort = SortType.Product;
                        break;
                    case "rdoSortNCC":
                        sort = SortType.Vendor;
                        break;
                    case "rdoSortPO":
                        sort = SortType.PurchaseOrder;
                        break;
                    case "rdoSortWeight":
                        sort = SortType.Weight;
                        break;
                    case "rdoSortCategory":
                        sort = SortType.WBS;
                        break;
                    default:
                        sort = SortType.None;
                        break;
                }
            }
        }

        private void rdoReport_CheckedChanged(object sender, EventArgs e)
        {
            if (sender is RadioButton)
            {
                RadioButton radioReport = sender as RadioButton;
                switch (radioReport.Name)
                {
                    case "rdoDate":
                    case "rdoProduct":
                    case "rdoVendor":
                    case "rdoVehicle":
                    case "rdoPO":
                        if (radioReport.Checked)
                        {
                            this.groupBox1.Enabled = false;
                            sort = SortType.None;
                        }
                        break;
                    case "rdoNhapHang":
                        cboPoType.SelectedIndex = (int)PurchaseType.Receive;
                        if (radioReport.Checked)
                        {
                            this.groupBox1.Enabled = true;
                            rdoSortDate.Checked = true;
                        }
                        break;
                    case "rdoXuatHang":
                        cboPoType.SelectedIndex = (int)PurchaseType.ShipOut;
                        if (radioReport.Checked)
                        {
                            this.groupBox1.Enabled = true;
                            rdoSortDate.Checked = true;
                        }
                        break;
                    case "rdoSummary":
                        if (radioReport.Checked)
                        {
                           // this.panel1.Enabled = false;
                            this.groupBox1.Enabled = false;
                            sort = SortType.None;
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        private void btnExcel_Click(object sender, EventArgs e)
        {
            string vehicleID = txtVehicleID.Text;
            LoadPurchaseOrders(vehicleID);

            if (null != poList && poList.Count > 0)
            {
                string times1, times2;
                IList<TitleClass> titles = new List<TitleClass>();
                List<HeaderClass> headers = new List<HeaderClass>();

                switch (cboPoType.SelectedIndex)
                {
                    case 1:
                        times1 = "TL Hàng và xe";
                        times2 = "TL Xe không";
                        break;
                    case 2:
                        times1 = "TL Xe không";
                        times2 = "TL Hàng và xe";
                        break;
                    default:
                        times1 = "Lần cân 1";
                        times2 = "Lần cân 2";
                        break;
                }

                if (rdoDate.Checked)
                {
                    titles.Add(new TitleClass()
                    {
                        Row = 1,
                        Col = 0,
                        Bold = true,
                        Text = "BÁO CÁO THEO NGÀY",
                        Size = 14,
                        Merge = true,
                        Align = Excel.Constants.xlCenter
                    });

                    headers.AddRange(new HeaderClass[] {
                        new HeaderClass() { Text = "Số phiếu", DataMember="POCode" },
                        new HeaderClass() { Text = "Số xe", DataMember="VehicleID" },
                        new HeaderClass() { Text = "Khách hàng", DataMember="VendorName" },
                        new HeaderClass() { Text = "Số PO", DataMember="PoID" },
                        new HeaderClass() { Text = "Hàng hóa", DataMember="ProductName" },
                        new HeaderClass() { Text = times1, DataMember="FirstWeight" },
                        new HeaderClass() { Text = times2, DataMember="SecondWeight" },
                        new HeaderClass() { Text = "TL Hàng", DataMember="ActualWeight" }
                    });
                }
                else if (rdoProduct.Checked)
                {
                    titles.Add(new TitleClass()
                    {
                        Row = 1,
                        Col = 0,
                        Bold = true,
                        Text = "BÁO CÁO THEO HÀNG HÓA",
                        Size = 14,
                        Merge = true,
                        Align = Excel.Constants.xlCenter
                    });

                    headers.AddRange(new HeaderClass[] {
                        new HeaderClass() { Text = "Số phiếu", DataMember="POCode" },
                        new HeaderClass() { Text = "Số xe", DataMember="VehicleID" },
                        new HeaderClass() { Text = "Khách hàng", DataMember="VendorName" },
                        new HeaderClass() { Text = "Ngày giờ", DataMember="ScaleTime2" },
                        new HeaderClass() { Text = times1, DataMember="FirstWeight" },
                        new HeaderClass() { Text = times2, DataMember="SecondWeight" },
                        new HeaderClass() { Text = "TL Hàng", DataMember="ActualWeight" },
                        new HeaderClass() { Text = "Số PO", DataMember="PoID" }
                    });
                }
                else if (rdoVendor.Checked)
                {
                    titles.Add(new TitleClass()
                    {
                        Row = 1,
                        Col = 0,
                        Bold = true,
                        Text = "BÁO CÁO THEO KHÁCH HÀNG",
                        Size = 14,
                        Merge = true,
                        Align = Excel.Constants.xlCenter
                    });

                    headers.AddRange(new HeaderClass[] {
                        new HeaderClass() { Text = "Số phiếu", DataMember="POCode" },
                        new HeaderClass() { Text = "Số xe", DataMember="VehicleID" },
                        new HeaderClass() { Text = "Hàng hóa", DataMember="ProductName" },
                        new HeaderClass() { Text = "Ngày giờ", DataMember="ScaleTime2" },
                        new HeaderClass() { Text = times1, DataMember="FirstWeight" },
                        new HeaderClass() { Text = times2, DataMember="SecondWeight" },
                        new HeaderClass() { Text = "TL Hàng", DataMember="ActualWeight" },
                        new HeaderClass() { Text = "Số PO", DataMember="PoID" }
                    });
                }
                else if (rdoPO.Checked)
                {
                    titles.Add(new TitleClass()
                    {
                        Row = 1,
                        Col = 0,
                        Bold = true,
                        Text = "BÁO CÁO THEO SỐ PO",
                        Size = 14,
                        Merge = true,
                        Align = Excel.Constants.xlCenter
                    });

                    headers.AddRange(new HeaderClass[] {
                        new HeaderClass() { Text = "Số phiếu", DataMember="POCode" },
                        new HeaderClass() { Text = "Số xe", DataMember="VehicleID" },
                        new HeaderClass() { Text = "Khách hàng", DataMember="VendorName" },
                        new HeaderClass() { Text = "Hàng hóa", DataMember="ProductName" },
                        new HeaderClass() { Text = times1, DataMember="FirstWeight" },
                        new HeaderClass() { Text = times2, DataMember="SecondWeight" },
                        new HeaderClass() { Text = "TL Hàng", DataMember="ActualWeight" }
                    });
                }
                else if (rdoVehicle.Checked)
                {
                    titles.Add(new TitleClass()
                    {
                        Row = 1,
                        Col = 0,
                        Bold = true,
                        Text = "BÁO CÁO THEO SỐ XE",
                        Size = 14,
                        Merge = true,
                        Align = Excel.Constants.xlCenter
                    });

                    headers.AddRange(new HeaderClass[] {
                        new HeaderClass() { Text = "Số phiếu", DataMember="POCode" },
                        new HeaderClass() { Text = "Khách hàng", DataMember="VendorName" },
                        new HeaderClass() { Text = "Hàng hóa", DataMember="ProductName" },
                        new HeaderClass() { Text = times1, DataMember="FirstWeight" },
                        new HeaderClass() { Text = times2, DataMember="SecondWeight" },
                        new HeaderClass() { Text = "TL Hàng", DataMember="ActualWeight" },
                        new HeaderClass() { Text = "Số PO", DataMember="PoID" }
                    });
                }
                else if (rdoNhapHang.Checked)
                {
                    titles.Add(new TitleClass()
                    {
                        Row = 1,
                        Col = 0,
                        Bold = true,
                        Text = "BÁO CÁO NHẬP HÀNG",
                        Size = 14,
                        Merge = true,
                        Align = Excel.Constants.xlCenter
                    });

                    headers.AddRange(new HeaderClass[] {
                        new HeaderClass() { Text = "Ngày giờ vào", DataMember="ScaleTime1" },
                        new HeaderClass() { Text = "Ngày giờ ra", DataMember="ScaleTime2" },
                        new HeaderClass() { Text = "Số Series", DataMember="SeriesNumber" },
                        new HeaderClass() { Text = "Số xe", DataMember="VehicleID" },
                        new HeaderClass() { Text = "Mã hàng", DataMember="ProductID" },
                        new HeaderClass() { Text = "Tên hàng", DataMember="ProductName" },
                        new HeaderClass() { Text = "Mã NCC", DataMember="VendorID" },
                        new HeaderClass() { Text = "Tên NCC", DataMember="VendorName" },
                        new HeaderClass() { Text = "PO#", DataMember="PoID" },                        
                        new HeaderClass() { Text = "Trọng lượng hàng", DataMember="ActualWeight" },                        
                        new HeaderClass() { Text = "Hạng mục", DataMember="WBS" },
                        new HeaderClass() { Text = "ĐVT2", DataMember="Unit2" },
                        new HeaderClass() { Text = "Số lượng 2", DataMember="ActualWeight2" }
                    });
                }
                else if (rdoXuatHang.Checked)
                {
                    titles.Add(new TitleClass()
                    {
                        Row = 1,
                        Col = 0,
                        Bold = true,
                        Text = "BÁO CÁO XUẤT HÀNG",
                        Size = 14,
                        Merge = true,
                        Align = Excel.Constants.xlCenter
                    });

                    headers.AddRange(new HeaderClass[] {
                        new HeaderClass() { Text = "Ngày giờ vào", DataMember="ScaleTime1" },
                        new HeaderClass() { Text = "Ngày giờ ra", DataMember="ScaleTime2" },
                        new HeaderClass() { Text = "Số Series", DataMember="SeriesNumber" },
                        new HeaderClass() { Text = "Số xe", DataMember="VehicleID" },
                        new HeaderClass() { Text = "Mã hàng", DataMember="ProductID" },
                        new HeaderClass() { Text = "Tên hàng", DataMember="ProductName" },
                        new HeaderClass() { Text = "Mã NCC", DataMember="VendorID" },
                        new HeaderClass() { Text = "Tên NCC", DataMember="VendorName" },
                        new HeaderClass() { Text = "PO#", DataMember="PoID" },                        
                        new HeaderClass() { Text = "Trọng lượng hàng", DataMember="ActualWeight" },                        
                        new HeaderClass() { Text = "Hạng mục", DataMember="WBS" },
                        new HeaderClass() { Text = "ĐVT2", DataMember="Unit2" },
                        new HeaderClass() { Text = "Số lượng 2", DataMember="ActualWeight2" }
                    });
                }
                else
                {
                    titles.Add(new TitleClass()
                    {
                        Row = 1,
                        Col = 0,
                        Bold = true,
                        Text = "BÁO CÁO TỔNG TRỌNG LƯỢNG NHẬP XUẤT",
                        Size = 14,
                        Merge = true,
                        Align = Excel.Constants.xlCenter
                    });

                    headers.AddRange(new HeaderClass[] {
                        new HeaderClass() { Text = "Số phiếu", DataMember="POCode" },
                        new HeaderClass() { Text = "Hàng hóa", DataMember="ProductName" },
                        new HeaderClass() { Text = "Khách hàng", DataMember="VendorName" },
                        new HeaderClass() { Text = "Trọng lượng", DataMember="ActualWeight" },
                        new HeaderClass() { Text = "Loại", DataMember="StringPOType" },
                        new HeaderClass() { Text = "Ghi chú" }
                    });
                }

                if ((rdoNhapHang.Checked) || (rdoXuatHang.Checked))
                {
                    string fromToDate = String.Format("Từ ngày {0:d} {0:HH:mm}", this.dateTimePicker1.Value);
                    titles.Add(new TitleClass() { Row = 2, Col = 1, Bold = false, Text = fromToDate, Size = 10 });
                    string ToDate = String.Format("Đến ngày {0:d} {0:HH:mm}",this.dateTimePicker2.Value);
                    titles.Add(new TitleClass() { Row = 2, Col = 3, Bold = false, Size = 10, Text = ToDate });
                    titles.Add(new TitleClass() { Row = 2, Col = 5, Bold = false, Text = "Mã hàng", Size = 10 });
                    titles.Add(new TitleClass() { Row = 2, Col = 6, Bold = false, Text = this.txtProductID.Text, Size = 10 });
                    titles.Add(new TitleClass() { Row = 2, Col = 7, Bold = false, Text = "Mã NCC/KH", Size = 10 });
                    titles.Add(new TitleClass() { Row = 2, Col = 8, Bold = false, Text = this.txtVendorID.Text, Size = 10 });
                    titles.Add(new TitleClass() { Row = 2, Col = 9, Bold = false, Text = "PO#", Size = 10 });
                    titles.Add(new TitleClass() { Row = 2, Col = 10, Bold = false, Text = this.txtPOID.Text, Size = 10 });
                    
                }
                else
                {
                    titles.Add(new TitleClass()
                    {
                        Row = 2,
                        Col = 3,
                        Bold = false,
                        Size = 10,
                        Text = String.Format("Từ {0:d} {0:HH:mm} Đến {1:d} {1:HH:mm}", this.dateTimePicker1.Value, this.dateTimePicker2.Value)
                    });
                    titles.Add(new TitleClass()
                    {
                        Row = 3,
                        Col = 3,
                        Bold = false,
                        Size = 10,
                        Text = "Khách: " + (cboVendorName.SelectedIndex > 0 ? cboVendorName.Text : define.UNKNOWN)
                    });
                    titles.Add(new TitleClass()
                    {
                        Row = 3,
                        Col = 5,
                        Bold = false,
                        Size = 10,
                        Text = "Hàng hóa: " + (cboProductName.SelectedIndex > 0 ? cboProductName.Text : define.UNKNOWN)
                    });
                    titles.Add(new TitleClass()
                    {
                        Row = 4,
                        Col = 3,
                        Bold = false,
                        Size = 10,
                        Text = "Số xe: " + (String.IsNullOrEmpty(vehicleID) ? define.UNKNOWN : vehicleID)
                    });
                }

                ReportDB.exportDataToExcel(titles, headers, poList.ToTable("VSSTQH_POModel"));
                MessageBoxEx.ShowSuccessful("Đã lưu Excel thành công.");

            }
            else
            {
                MessageBoxEx.ShowAlert("Từ {0:d} {0:HH:mm} Đến {1:d} {1:HH:mm} không có cân xe!", dateTimePicker1.Value, dateTimePicker2.Value);
            }
        }

        private void btnViewReport_Click(object sender, EventArgs e)
        {
            string vehicleID = txtVehicleID.Text;
            LoadPurchaseOrders(vehicleID);

            if (null != poList && poList.Count > 0)
            {
                ReportDocument report = null;

                if (rdoDate.Checked)
                {
                    report = new crReportDate();
                }
                else if (rdoProduct.Checked)
                {
                    report = new crReportProduct();
                }
                else if (rdoVendor.Checked)
                {

                    report = new crReportVendor();
                }
                else if (rdoPO.Checked)
                {
                    report = new crReportPO();
                }
                else if (rdoVehicle.Checked)
                {

                    report = new crReportVehicle();
                }
                else if (rdoNhapHang.Checked)
                {
                    report = new crReportNhapHang();

                }
                else if (rdoXuatHang.Checked)
                {
                    report = new crReportXHang();
                }
                else
                {
                    this.groupBox1.Enabled = false;
                    report = new crReportSummary();
                }

                if (report != null)
                {
                    report.SetDataSource(poList.ToTable("PO"));

                    report.SetParameterValue("FromDate", String.Format("{0:d} {0:HH:mm}", this.dateTimePicker1.Value));
                    report.SetParameterValue("ToDate", String.Format("{0:d} {0:HH:mm}", this.dateTimePicker2.Value));
                    report.SetParameterValue("VendorName", cboVendorName.SelectedIndex > 0 ? cboVendorName.Text : define.UNKNOWN);
                    report.SetParameterValue("ProductName", cboProductName.SelectedIndex > 0 ? cboProductName.Text : define.UNKNOWN);
                    report.SetParameterValue("VehicleID", String.IsNullOrEmpty(vehicleID) ? define.UNKNOWN : vehicleID);
                    if (rdoNhapHang.Checked || rdoXuatHang.Checked)
                    {
                        report.SetParameterValue("ProductID", this.txtProductID.Text.Length > 0 ? this.txtProductID.Text : define.UNKNOWN);
                        report.SetParameterValue("VendorID", this.txtVendorID.Text.Length > 0 ? this.txtVendorID.Text : define.UNKNOWN);
                        report.SetParameterValue("POID", this.txtPOID.Text.Length > 0 ? this.txtPOID.Text : define.UNKNOWN);
                    }
                    Configuration config = new Configuration();
                    if (Common.CheckPrinter(config.ReceiptPrintName))
                        report.PrintOptions.PrinterName = config.ReportPrintName;

                    if (config.IsPreviewReportPrint)
                    {
                        // Print preview
                        FrmPrintPreview form = new FrmPrintPreview(report);
                        form.ShowDialog();
                    }
                    else
                    {
                        // Print without preview
                        report.PrintToPrinter(1, false, 0, 0);
                    }
                }
            }
            else
            {
                MessageBoxEx.ShowAlert("Từ {0:d} {0:HH:mm} đến {1:d} {1:HH:mm} không có cân xe!", dateTimePicker1.Value, dateTimePicker2.Value);
            }

        }

        private void cboVendor_SelectedValueChanged(object sender, KeyEventArgs e)
        {
            txtVendorID.Text = (cboVendorName.SelectedValue ?? String.Empty).ToString();
        }

        private void cboProduct_SelectedValueChanged(object sender, KeyEventArgs e)
        {
            txtProductID.Text = (cboProductName.SelectedValue ?? String.Empty).ToString();
        }

        #endregion

        #region Methods

        private void LoadCombos()
        {
            IProductDAO dao = new ProductDAO();
            IList<ProductModel> products = dao.GetAll().OrderBy(x => x.ProductName).ToList();

            if (null != products)
            {
                products.Insert(0, new ProductModel() { ProductName = String.Empty });
                this.cboProductName.AddDataSource(products.ToTable(), "ProductName", "ProductID");
            }

            IVendorDAO dao1 = new VendorDAO();
            IList<VendorModel> vendors = dao1.GetAll();
            if (null != vendors)
            {
                vendors.Insert(0, new VendorModel() { VendorName = String.Empty });
                this.cboVendorName.AddDataSource(vendors.ToTable(), "VendorName", "VendorID");
            }

            IPODAO dao2 = new PODAO();
            IList<POModel> pos = dao2.GetAll();
            if (null != pos)
            {
                pos.Insert(0, new POModel() { PoID = String.Empty });
                this.txtPOID.AddDataSource(pos.ToTable(), "PoID", "PoID");
            }
        }

        private void LoadPurchaseOrders(string vehicleID)
        {
            IPODAO dao = new PODAO();
            string vendorID = txtVendorID.Text;
            string productID = txtProductID.Text;
            string poID = txtPOID.Text;

            if (sort == SortType.None)
            {
                poList = dao.Search(this.dateTimePicker1.Value, this.dateTimePicker2.Value,
                   vendorID, productID, (PurchaseType)cboPoType.SelectedIndex, vehicleID, poID).OrderBy(p => p.POCode).ToList();
            }
            else
            {
                poList = dao.SortSearch(this.dateTimePicker1.Value, this.dateTimePicker2.Value,
                    (PurchaseType)cboPoType.SelectedIndex, sort);
            }
        }

        #endregion
    }
}
